<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { addBrrow } from '@/api/archives';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import selectArchives from '../component/selectArchives.vue';
  import selectSign from '@/components/selectSign/index.vue';
  import { transformDeptTreeSelect } from '@/utils/utils';
  import { useUserStore } from '@/store';
  import { getDeptSelect } from '@/api/syssetting';
  import { getAllUser } from '@/api/user';

  const formRef = ref<FormInstance | null>(null);
  const props = defineProps({
    visible: Boolean,
  });
  const signUrl = ref<string | null>(null);
  const visible2 = ref(false);
  const { loading, setLoading } = useLoading();
  defineOptions({
    name: 'userAddSetting',
  });
  const userStore = useUserStore();

  const formData = ref({});
  const emit = defineEmits(['update:visible', 'refresh']);
  const showModel = ref(false);
  const handleSubmit = async () => {
    if (selectItem.value.length <= 0) {
      Message.warning('请选择借阅档案');
      return false;
    }

    try {
      // 先验证表单基础校验
      if (!formRef.value?.checkForm()) {
        return;
      }

      // 使用 for 循环替代 map 实现短路终止
      const borrowDetails = [];
      for (const item of selectItem.value) {
        if (!item.num) {
          // 显示具体错误位置
          Message.error(`档案 ${item.arc_name} 未填写借阅数量`);
          return; // 立即终止执行
        }
        borrowDetails.push({
          arc_id: item.arc_id,
          arc_num: item.num,
        });
      }

      if (!signUrl.value) {
        Message.error(`请选择签章！`);
        return false;
      }

      // 所有校验通过后执行提交
      setLoading(true);
      const res = await addBrrow({
        borrow_user_contact: formRef.value?.formModel.borrow_user_contact,
        borrow_start_time: formRef.value?.formModel.borrow_start_time[0],
        borrow_end_time: formRef.value?.formModel.borrow_start_time[1],
        borrow_arc_type: formRef.value?.formModel.borrow_arc_type,
        borrow_org_id: formRef.value?.formModel.borrow_org_id,
        borrow_dept_id: formRef.value?.formModel.borrow_dept_id,
        borrow_user_id: formRef.value?.formModel.borrow_user_id,
        borrow_detail: borrowDetails,
        borrow_type: formRef.value?.formModel.borrow_type,
        borrow_user_sign: signUrl.value,
        borrow_remark: formRef.value?.formModel.borrow_remark || '',
      });

      Message.success(res.msg);
      emit('update:visible', false);
      emit('refresh');
    } catch (error) {
      // Message.error('提交失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };
  const selectItem = ref([]);
  const handleSelectArchive = (e: any) => {
    selectItem.value = e.map((item: any) => ({
      ...item,
      num: '', // 默认值设为1
    }));
  };
  const type = ref();
  function handleShowModal() {
    if (formRef.value?.formModel.borrow_arc_type) {
      type.value = formRef.value?.formModel.borrow_arc_type;
      showModel.value = true;
    } else {
      Message.warning('请先选择档案类型！');
    }
  }

  const sonFormType = ref([
    {
      name: 'borrow_arc_type',
      label: '档案类型',
      type: 'a-select',
      fieldProps: {
        span: 24,
        allowSearch: true,
        fieldNames: { value: 'cvalue', label: 'clabel' },
      },
      selectOptions: [
        {
          clabel: '综合档案',
          cvalue: 1,
        },
        {
          clabel: '证照档案',
          cvalue: 2,
        },
        {
          clabel: '人事档案',
          cvalue: 3,
        },
        {
          clabel: '财务档案',
          cvalue: 4,
        },
        {
          clabel: '申报档案',
          cvalue: 5,
        },
        {
          clabel: '技术档案',
          cvalue: 6,
        },
      ],
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      name: 'borrow_type',
      label: '借阅方式',
      type: 'a-select',
      fieldProps: {
        span: 24,
        allowSearch: true,
      },
      selectOptions: [
        {
          label: '本人自提',
          value: 1,
        },
        {
          label: '快递邮寄',
          value: 2,
        },
      ],
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      name: 'borrow_org_id',
      label: '所属单位',
      type: 'a-select',
      fieldProps: {
        span: 24,
        allowSearch: true,
        fieldNames: { value: 'org_id', label: 'org_name' },
      },
      selectOptions: userStore.allOrgList,
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      name: 'borrow_dept_id',
      label: '所属部门',
      type: 'a-tree-select',
      fieldProps: {
        span: 24,
        data: transformDeptTreeSelect(userStore.allDept, 'dept_id', 'dept_id'),
      },
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      name: 'borrow_user_id',
      label: '借阅人',
      type: 'a-select',
      fieldProps: {
        span: 24,
        fieldNames: { value: 'user_id', label: 'user_name' },
        allowSearch: true,
      },
      selectOptions: [],
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },

    {
      name: 'borrow_start_time',
      label: '借阅时间范围',
      type: 'a-range-picker',
      fieldProps: {
        span: 24,
      },
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },
    {
      name: 'borrow_user_contact',
      label: '联系电话',
      type: 'a-input-number',
      fieldProps: {
        span: 24,
        maxLength: 11,
      },
      rules: [
        {
          message: '请选择',
          required: true,
        },
      ],
    },

    {
      name: 'borrow_remark',
      label: '备注',
      type: 'a-textarea',
      fieldProps: {
        span: 24,
      },
    },
  ]);
  //   监听所属单位改变修改部门
  const currentDetps = ref();
  watch(
    () => formRef.value?.formModel.borrow_org_id,
    (newVal) => {
      getDeptSelect({
        dept_org_id: newVal,
      }).then((res) => {
        formRef.value?.setFormItm('borrow_dept_id', '');
        formRef.value?.setFormItm('borrow_user_id', '');
        currentDetps.value = transformDeptTreeSelect(
          res.data,
          'dept_id',
          'dept_id'
        );
        sonFormType.value = [
          {
            name: 'borrow_arc_type',
            label: '档案类型',
            type: 'a-select',
            fieldProps: {
              span: 24,
              allowSearch: true,
              fieldNames: { value: 'cvalue', label: 'clabel' },
            },
            selectOptions: [
              {
                clabel: '综合档案',
                cvalue: 1,
              },
              {
                clabel: '证照档案',
                cvalue: 2,
              },
              {
                clabel: '人事档案',
                cvalue: 3,
              },
              {
                clabel: '财务档案',
                cvalue: 4,
              },
              {
                clabel: '申报档案',
                cvalue: 5,
              },
              {
                clabel: '技术档案',
                cvalue: 6,
              },
            ],
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_type',
            label: '借阅方式',
            type: 'a-select',
            fieldProps: {
              span: 24,
              allowSearch: true,
            },
            selectOptions: [
              {
                label: '本人自提',
                value: 1,
              },
              {
                label: '快递邮寄',
                value: 2,
              },
            ],
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_org_id',
            label: '所属单位',
            type: 'a-select',
            fieldProps: {
              span: 24,
              allowSearch: true,
              fieldNames: { value: 'org_id', label: 'org_name' },
            },
            selectOptions: userStore.allOrgList,
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_dept_id',
            label: '所属部门',
            type: 'a-tree-select',
            fieldProps: {
              span: 24,
              data: transformDeptTreeSelect(res.data, 'dept_id', 'dept_id'),
            },
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_user_id',
            label: '借阅人',
            type: 'a-select',
            fieldProps: {
              span: 24,
              fieldNames: { value: 'user_id', label: 'user_name' },
              allowSearch: true,
            },
            selectOptions: [],
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_start_time',
            label: '借阅时间范围',
            type: 'a-range-picker',
            fieldProps: {
              span: 24,
            },
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_user_contact',
            label: '联系电话',
            type: 'a-input-number',
            fieldProps: {
              span: 24,
              maxLength: 11,
            },
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_remark',
            label: '备注',
            type: 'a-textarea',
            fieldProps: {
              span: 24,
            },
          },
        ];
      });
    }
  );
  //   监听所诉部门改变修改用户
  watch(
    () => formRef.value?.formModel.borrow_dept_id,
    (newVal) => {
      getAllUser({
        dept_id: newVal,
      }).then((res) => {
        formRef.value?.setFormItm('borrow_user_id', '');
        sonFormType.value = [
          {
            name: 'borrow_arc_type',
            label: '档案类型',
            type: 'a-select',
            fieldProps: {
              span: 24,
              allowSearch: true,
              fieldNames: { value: 'cvalue', label: 'clabel' },
            },
            selectOptions: [
              {
                clabel: '综合档案',
                cvalue: 1,
              },
              {
                clabel: '证照档案',
                cvalue: 2,
              },
              {
                clabel: '人事档案',
                cvalue: 3,
              },
              {
                clabel: '财务档案',
                cvalue: 4,
              },
              {
                clabel: '申报档案',
                cvalue: 5,
              },
              {
                clabel: '技术档案',
                cvalue: 6,
              },
            ],
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_type',
            label: '借阅方式',
            type: 'a-select',
            fieldProps: {
              span: 24,
              allowSearch: true,
            },
            selectOptions: [
              {
                label: '本人自提',
                value: 1,
              },
              {
                label: '快递邮寄',
                value: 2,
              },
            ],
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_org_id',
            label: '所属单位',
            type: 'a-select',
            fieldProps: {
              span: 24,
              allowSearch: true,
              fieldNames: { value: 'org_id', label: 'org_name' },
            },
            selectOptions: userStore.allOrgList,
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },

          {
            name: 'borrow_dept_id',
            label: '所属部门',
            type: 'a-tree-select',
            fieldProps: {
              span: 24,
              data: currentDetps.value,
            },
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_user_id',
            label: '借阅人',
            type: 'a-select',
            fieldProps: {
              span: 24,
              fieldNames: { value: 'user_id', label: 'user_name' },
              allowSearch: true,
            },
            selectOptions: res.data,
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_start_time',
            label: '借阅时间范围',
            type: 'a-range-picker',
            fieldProps: {
              span: 24,
            },
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_user_contact',
            label: '联系电话',
            type: 'a-input-number',
            fieldProps: {
              span: 24,
              maxLength: 11,
            },
            rules: [
              {
                message: '请选择',
                required: true,
              },
            ],
          },
          {
            name: 'borrow_remark',
            label: '备注',
            type: 'a-textarea',
            fieldProps: {
              span: 24,
            },
          },
        ];
      });
    }
  );
  const selectAlready = (url) => {
    signUrl.value = url;
  };
</script>

<template>
  <a-modal
    title="借阅申请"
    :visible="visible"
    @ok="handleSubmit"
    title-align="start"
    :ok-loading="loading"
    @cancel="
      () => {
        emit('update:visible', false);
      }
    "
  >
    <a-row style="margin-left: 6.8rem; margin-bottom: 25px">
      <a-button @click="handleShowModal">
        <template #icon>
          <icon-find-replace />
        </template>
        <template #default>选择借阅档案</template>
      </a-button>
      <a-col :span="24">
        <a-card
          hoverable
          class="iscard"
          v-for="(item, index) in selectItem"
          :key="index"
        >
          <div class="cardBox">
            <span class="cardItem">
              <a-avatar
                :style="{ marginRight: '8px', backgroundColor: '#165DFF' }"
                :size="28"
              >
                {{ item.arc_type_name.slice(0, 1) }}
              </a-avatar>
              <a-typography-text>{{ item.arc_name }}</a-typography-text>
            </span>
            <div style="width: 152px">
              <a-input
                v-model="item.num"
                placeholder="请输入借阅文档数量"
                type="number"
                :min="1"
                :max="9999"
              />
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <pro-form
      ref="formRef"
      hiddenBtn
      :form-json="sonFormType"
      :form-data="formData"
    ></pro-form>
    <select-archives
      v-if="showModel"
      v-model:visible="showModel"
      :type="type"
      @selectArchives="handleSelectArchive"
    />
    <!--  选择签名  -->
    <a-row
      style="
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-left: 70px;
      "
    >
      <span style="max-width: 100%; font-size: 14px; white-space: normal"
        >签章</span
      >
      <a-button
        style="margin-left: 15px"
        @click="
          () => {
            visible2 = true;
          }
        "
      >
        <template #icon>
          <icon-stamp />
        </template>
        <template #default>选择签章</template>
      </a-button>
    </a-row>
    <selectSign v-model:visible="visible2" @selected="selectAlready" />
    <div
      style="width: 100px; margin-left: 100px; margin-top: 5px"
      v-if="signUrl"
    >
      <a-image fit="contain" height="100%" width="100%" :src="signUrl" />
    </div>
  </a-modal>
</template>

<style scoped lang="less">
  :deep(.arco-select-view-inner) {
    text-align: left !important;
  }
  .iscard {
    width: 360px;
    margin-bottom: 10px;
    margin-top: 10px;
  }
  .cardBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .cardItem {
    display: flex;
    align-items: center;
    color: #1d2129;
  }
</style>
